<template>
	<div>
		<div v-show="!showhandsign">
			<header class="ui-header">
				<i class="ui-icon-back cursor-point" @click="back()"></i>
				<span class="title">{{ $t('ivcs.agent') }}</span>
			</header>

			<footer class="ui-footer bg-white" :class="showTools ? 'h-120' : 'h-50'">
				<section class="main">
					<!-- 文本输入 -->
					<div class="write_box" id="write_box">
						<div class="body" @input="changeText" @focus="inputFocus" contenteditable="true"></div>
					</div>
					<div class="tool-box">
						<i class="ui-icon-add cursor-point" @click.prevent="showOrHideTools"></i>
						<div class="right">
							<div class="tools"></div>
							<Dropdown @on-click="sendcommonmessage">
								<span class="ui-button-phrase cursor-point" v-show="inputMessage ? false : true">{{ $t('ivcs.normalword') }}</span>
								<DropdownMenu slot="list">
									<DropdownItem v-for="(raw, index) in commonList" :name="raw.id" :key="index">{{ raw.value }}</DropdownItem>
								</DropdownMenu>
							</Dropdown>
							<span class="ui-button-send cursor-point" v-show="inputMessage ? true : false" @click="sendMessage">{{ $t('ivcs.send') }}</span>
						</div>
					</div>
				</section>
				<div class="line"></div>
				<div class="tool" v-show="showTools">
					<div class="cursor-point" onclick="document.getElementById('file').click()">
						<i class="ui-icon-sendpicture"></i>
						<br />
						<span>{{ $t('ivcs.sendpic') }}</span>
						<input style="display: none;" type="file" name="image" id="file" value="" accept="image/gif,image/png,image/jpeg,image/jpg,image/bmp" @change="sendPicture($event)" />
					</div>
					<div class="cursor-point" onclick="document.getElementById('file2').click()">
						<i class="ui-icon-sendfile"></i>
						<br />
						<span>{{ $t('ivcs.sendfile') }}</span>
						<input style="display: none;" type="file" name="file2" id="file2" value="" @change="sendFile($event)" />
					</div>
				</div>
			</footer>

			<section class="ui-container" ref="homePage">
				<ul class="chat-message">
					<li v-for="(chat, index) in messageData" :key="index" :class="chat.label === 'agent' ? 'an-move-left' : chat.label === 'customer' ? 'an-move-right' : ''">
						<p class="time" v-show="chat.label === 'system'">
							<span>{{ getFormatTime(chat.date) }}</span>
						</p>
						<p class="time" v-show="chat.showTime">
							<span>{{ chat.date }}</span>
						</p>

						<div class="system-msg" v-show="chat.label === 'system'">
							<span>{{ chat.data }}</span>
						</div>
						<div class="main">
							<chat-message :message="chat.data" :index="index" :name="chat.fromUser.name" :msgType="chat.type" :mediaId="chat.clientId" :fileurl="chat.fileurl" :type="chat.label" :isRobot="chat.fromUser.isRobot"></chat-message>
						</div>
					</li>
				</ul>
			</section>
			<div v-show="showImg" class="window-shadow"> </div>
			<div v-show="showImg" class="window-img">
				<img @click="closeFullImg" class="close" src="../../static/image/img/close.png" />
				<img src="" />
			</div>
		</div>
		<message ref="message"></message>
		<ccs-im ref="ccsIm"></ccs-im>
		<!-- 富文本 -->
		<RichText v-if="richText" :richText="richText" @close="closeRichText" />
	</div>
</template>

<script>
import ivcs from '../ivcs-sdk';
import { dateStr } from '../tool/tool';
import ChatMessage from './ChatMessage';
import Message from './Message';
import { sendMessageToRecord, formatMessageTime } from '../tool/util';
import { uploadFile, uploadBase64Image } from '../tool/uploadFile';
import CcsIm from './CcsIm';
import _ from 'lodash';
import RichText from '../components/RichText.vue';
import { mapMutations, mapState } from 'vuex';
export default {
	name: 'newIM',
	components: { CcsIm, Message, ChatMessage, RichText },
	props: ['audiovideo', 'members'],
	data() {
		return {
			isRobot: false,
			showhandsign: false,
			chatList: [],
			userid: localStorage.getItem('userId'),
			showImg: false,
			showPhrase: false, // 常用语按钮
			showSend: true, // 发送按钮
			showTools: false, // 工具栏
			inputMessage: null, // 聊天信息
			clientHeight: '', //当前屏幕高度, 用于将聊天框平铺整个手机
			commonList: [
				{ id: '1', value: this.$t('ivcs.word1') },
				{ id: '2', value: this.$t('ivcs.word2') }
			],
			sessionId: null,
			readystatus: false, //是否可以IM功能
			ticket: null,
			ccsinterval: null,
			browserInfo: null, //当前浏览器的信息
			ccsUrl: loginUrl,
			token: localStorage.getItem('customer_token'),
			isTransfer: false, //转接中,
			sessionData: null,
			startMsgTime: 0 // 第一条非系统消息时间
		};
	},
	computed: {
		...mapState({
			messageData: state => state.message.messageData,
			customer: state => state.user.customer,
			agentMembers: state => state.user.agentMembers,
			agent: state => state.user.agent,
			richText: state => state.message.richText
		})
	},
	mounted() {
		var that = this;
		that.clientHeight = document.documentElement.clientHeight;
		window.onresize = function temp() {
			that.clientHeight = `${document.documentElement.clientHeight}`;
		};
		that.initEmotion();
	},
	destroyed() {},
	watch: {
		clientHeight: function() {
			this.changeFixed(this.clientHeight);
		}
	},
	methods: {
		...mapMutations('message', ['SET_MESSAGE_DATA', 'SET_RICH_TEXT']),
		...mapMutations('user', ['SET_AGENT_INFO']),
		onForm() {
			ivcs.client.onForm(resp => {
				console.log('onForm, resp', resp);
				if (resp.data.inputform === 1) {
					//坐席发送表单，让访客填写提交表单,目前根据不同的技能组坐席发送不同的表单。
					this.$emit('inputform', resp.data.formTemplate);
				} else if (resp.data.collect === 1) {
					//坐席发送确认信息，请访客这边确认
					this.$emit('surecollectioninfo', resp.data);
				}
			});
		},

		//关闭富文本组件
		closeRichText() {
			this.$store.commit('SET_RICH_TEXT', '');
		},

		onTextMessage() {
			ivcs.client.onTextMessage(resp => {
				this.filterAgentByMsg(resp);
				if (!resp.data) {
					return;
				}
				var message = textFace2imgFace(resp.data);
				if (message.indexOf('stopMark') != -1) {
					//停止标注信息
					this.$emit('stopScreenMark');
					return;
				}
				if (message.indexOf('agentcollectionPic=') != -1) {
					//采集图片
					this.collectPic(message);
					return;
				}
				switch (message) {
					case 'silence-msg':
						message = '- -';
						break;
					case 'OnTaskFailed':
						message = '- -';
						break;
					default:
						message = resp.data;
						break;
				}
				let data = { text: textFace2imgFace(message), date: resp.createdAt };
				let msg = resp.from === this.customer.clientId ? sendMessageToRecord('text', data, this.customer) : sendMessageToRecord('text', data, this.agent);
				this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
				console.log('SET_MESSAGE_DATA:', this.messageData, this.agent);
				this.setMsgTimer();
				this.scrollToBottom();
				this.$emit('onTextMessage', resp);
			});
		},
		onCustomMessage() {
			let self = this;
			ivcs.client.onCustomMessage(resp => {
				if (resp.data.businessType == 'mark_trace') {
					let code = resp.data.message.track;
					this.$emit('startScreenMark', code);
					console.log('startScreen mark code', code);
				}
				if (resp.data.businessType === 'agent_collect_image') {
					//采集图片
					this.collectPic(resp.data.info);
				}
				if (resp.data.businessType && resp.data.businessType !== 'face_compare_result' && resp.data.businessType !== 'mark_trace' && resp.data.businessType !== 'system_msg' && resp.data.businessType !== 'stop_send_form' && resp.data.businessType !== 'collect-information') {
					let result = {
						type: 'service',
						date: dateStr(),
						message: resp.data.message
					};
					switch (resp.data.businessType) {
						case 'get_customer_location':
							result.message = result.message + ':' + resp.data.result.message;
							break;
					}
					self.chatList.push(result);
				}
				self.$emit('onCustomMessage', resp);
			});
		},

		onResourceMessage() {
			ivcs.client.onResourceMessage(resp => {
				console.log('receive resource message,', resp);
				this.filterAgentByMsg(resp);
				if (!resp.data) {
					return;
				}
				this.onSharedResource(resp);
			});
		},

		readyToTalk(selfId) {
			let user = {
				picture: localStorage.getItem('userPicture'),
				fullName: localStorage.getItem('fullName'),
				gender: localStorage.getItem('gender')
			};
			console.log('readyToTalk data', user, selfId);
			this.$refs.ccsIm.readyToTalk(selfId, user);
		},

		showErrorInfo(message, time) {
			this.$Notice.error({
				title: this.$t('ivcs.confirm'),
				desc: message,
				duration: time,
				top: 0
			});
		},

		ccsError(reason) {
			this.$Notice.error({
				title: this.$t('ivcs.confirm'),
				desc: this.$t('ivcs.systemerror') + '---' + reason,
				duration: 10,
				top: 0
			});
			this.$emit('ccserror');
		},

		//用户开始填写的表单信息发送给坐席
		sendCustomerInfoFormId() {
			this.sendMessageToAgent('formid=' + localStorage.getItem('userInfoFormId'), false);
		},

		joinRoom(isRobot) {
			this.$emit('joinroom', isRobot);
		},

		inviteInputForm(data) {
			this.$emit('inputform', data);
		},
		agentQuitSession(resp) {
			console.log('<<<<<<########agent quit session,', resp);
		},

		collectPic(data) {
			this.$emit('agentcollectionPic', data);
		},

		inviteMakeSureFormInfo(data) {
			this.$emit('surecollectioninfo', data);
		},

		holdon() {
			this.isTransfer = true;
			// this.$emit('transfer',1);//正在转接中
		},

		onScreenSnapshot() {
			this.$emit('snapshot');
		},

		gotoHandsign() {
			this.$emit('handsign');
		},

		receiveMessage(data) {
			var message = textFace2imgFace(data);
			if (message.indexOf('startMark') != -1) {
				//标注信息
				let code = message.substring(9);
				this.$emit('startScreenMark', code);
				console.log('startScreen mark code', code);
				return;
			}
			if (message.indexOf('stopMark') != -1 && typeof message === 'string') {
				//停止标注信息
				this.$emit('stopScreenMark');
				return;
			} else {
				var result = {
					type: 'service',
					date: dateStr(),
					message: message
				};
				console.log('receiveMessage:', data);
				this.chatList.push(result);
				this.scrollToBottom();
			}
		},

		onSharedResource(resp) {
			let msg;
			if (resp.data.type === 'pic') {
				//接收到照片
				let data = {
					type: 'pic',
					url: resp.data.url,
					fileName: resp.data.name
				};
				msg = sendMessageToRecord('link', data, this.agent);
				console.log(this.agent);
				this.scrollToBottom();
			} else if (resp.data.type === 'doc') {
				let data = {
					type: 'file',
					url: resp.data.url,
					name: resp.data.name,
					suffix: resp.data.suffix,
					size: resp.data.size
				};
				msg = sendMessageToRecord('link', data, this.agent);
				this.scrollToBottom();
			} else if (resp.data.type === 'paper') {
				let url = resp.data.url;
				this.$emit('gotocontract', url);
			} else if (resp.data.type === 'video') {
				let url = resp.data.url;
				this.$emit('sharevideourl', url);
			} else if (resp.data.type === 'page') {
				let url = resp.data.url;
				this.$emit('sharelinkurl', url);
			}
			this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
			this.setMsgTimer();
			console.log(this.messageData);
		},

		onDrop() {
			this.$Notice.info({
				title: this.$t('ivcs.confirm'),
				desc: this.$t('ivcs.systemdrop'),
				duration: 10,
				top: 0
			});
			this.$emit('AutoHangUp');
		},

		agentJoinSession(data) {
			console.log('<<<<<<############onJoinedSession:', data);
		},

		onInvitationProgress(data) {
			if (this.$store.state.sessionId) {
				console.log('is in session');
				return;
			}
			console.log('onInvitationProgress,,', data);
			//this
			let waitingNum = data.data.waitingNum;
			if (waitingNum == undefined) {
				waitingNum = 0;
			}
			this.$store.commit('setQueueNum', waitingNum);
			let currentPosition = data.data.position;
			if (currentPosition == undefined) {
				currentPosition = 0;
			}
			this.$store.commit('setCurrentPosition', currentPosition);
			var status = data.data ? data.data.status : '';
			if (status === 'timeout') {
				this.$Message.info({
					content: this.$t('ccs.timeout'),
					duration: 3
				});
				this.hangUpCall();
			} else if (status === 'notfound') {
				this.$Message.info({
					content: this.$t('ccs.notfound'),
					duration: 3
				});
				this.hangUpCall();
			} else if (status === 'waiting') {
				var waitingCode = data.data.waitingReasonCode;
				if (waitingCode) {
					if (waitingCode === '1000') {
						//正在分配坐席
					} else if (waitingCode === '1001') {
						//没有找到可用坐席
						this.isWaitConfirmView();
					} else if (waitingCode === '1002') {
						//指定坐席，坐席没登录
					} else if (waitingCode === '1003') {
						//指定坐席，坐席当前状态不可用，agentStatus=ringing/serving/notReady/otherWork
					} else if (waitingCode === '1004') {
						//指定坐席，坐席振铃时候断开
					}
				}
			} else if (status === 'accepted') {
				let agent = data.data.agent;
				this.$Modal && this.$Modal.remove();
				if (agent.user && agent.user.profile && agent.user.profile.isRobot) {
					//访客requestSession成功
					let interval = setInterval(() => {
						if (this.sessionData) {
							this.isRobot = true;
							this.joinRoom(true);
							clearInterval(interval);
						}
					}, 100);
				}
			}
		},

		isWaitConfirmView() {
			var self = this;
			this.$Modal.confirm({
				title: self.$t('ivcs.confirm'),
				content: self.$t('ccs.notAvailable'),
				okText: self.$t('ivcs.Yes'),
				cancelText: self.$t('ivcs.No'),
				onOk: () => {},
				onCancel: () => {
					//挂断
					self.hangUpCall();
				}
			});
		},

		hangUpCall() {
			this.$emit('AutoHangUp');
		},

		/*接通session会话后的加入房间的处理*/
		joinSession(data) {
			this.$emit('setroomid', data.roomId);
			this.$emit('setroomtoken', data.roomToken);
			this.$emit('setsessionId', data.sessionId);
			this.sessionId = data.sessionId;
			this.ticket = data.ticket;
			this.sessionData = data;
			console.log(`'join session success',${data},at ${_.now()}`);
			// this.$refs.ccsIm.businessListener();
		},

		/*hangup session*/
		quitSession() {
			var self = this;
			this.$refs.ccsIm
				.quitSession()
				.then(function(resp) {
					console.log('quitSession success', resp);
				})
				.catch(function(error) {
					var message = 'quit session failed' + error;
					self.showErrorInfo(message, 3);
				});
			this.$store.commit('setSessionId', null);
		},

		/*client send message to agent*/
		sendMessage() {
			var text = $('.body').html();
			if (text == '') {
				this.$Message.error(this.$t('ivcs.messagenull'));
				$('.body').focus();
				return;
			}
			text = imgFace2textFace(
				text
					.replace(/<br>/gi, '\n')
					.replace(/<div>/gi, '\n')
					.replace(/<(?!img|embed).*?>/gi, '')
					.replace(/&nbsp;/gi, ' ')
			);
			console.log('sendText:', text);
			this.sendMessageToAgent(text);
		},

		/*发送常用语*/
		sendcommonmessage(value) {
			console.log(value);
			var text;
			if (value == 1) {
				text = this.$t('ivcs.word1');
			} else {
				text = this.$t('ivcs.word2');
			}
			this.sendMessageToAgent(text);
		},

		/**
		 * 发送确认消息给坐席
		 * */
		sendMessageConfirmationToAgent(data, clientId) {
			ivcs.client.sendMessageConfirmation(
				data,
				clientId,
				resp => {
					console.log('sendMessageConfirmationToAgent succes', resp);
				},
				error => {
					console.log('sendMessageConfirmationToAgent error', error);
				}
			);
		},

		/*发送消息给坐席,消息+随路数据*/
		sendMessageToAgent(message, needAddChatHistory = true) {
			var self = this;
			this.$Spin.show();
			ivcs.client.sendTextMessage(
				message,
				undefined,
				resp => {
					console.log('send success', resp);
					this.$Spin.hide();
					$('.body').html('');
					self.inputMessage = '';
					self.scrollToBottom();
					if (needAddChatHistory) {
						let msg = sendMessageToRecord('text', textFace2imgFace(message), this.customer);
						self.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
						this.setMsgTimer();
					}
				},
				error => {
					this.$Spin.hide();
					console.log('send error', error);
					self.$Message.error(self.$t('ivcs.sendfailed'));
				}
			);
		},

		sendImageToAgent(imagetext, data, needAddToHistory) {
			this.$Spin.show();
			console.log('imgData:', data);
			ivcs.client.shareResourceWithFileInfo(
				'pic',
				data,
				'others',
				resp => {
					$('.body').html('');
					this.inputMessage = '';
					this.scrollToBottom();
					let msgData = {
						url: data.url,
						type: 'pic',
						name: data.name
					};
					console.log('shareResourceWithFileInfo resp', resp);
					if (needAddToHistory) {
						let msg = sendMessageToRecord('link', msgData, this.customer);
						this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
						this.setMsgTimer();
					}
					this.sendMessageConfirmationToAgent(data);
				},
				error => {
					console.log('send pic Message failed', error);
					this.$Message.error(this.$t('ivcs.sendfailed'));
				}
			);
			this.$Spin.hide();
		},

		sendFileToAgent(message, data) {
			this.$Spin.show();
			ivcs.client.shareResourceWithFileInfo(
				'doc',
				data,
				'agents',
				resp => {
					this.$Spin.hide();
					$('.body').html('');
					this.inputMessage = '';
					this.scrollToBottom();
					console.log('shareResourceWithFileInfo resp', resp);
				},
				error => {
					this.$Spin.hide();
					console.log('send file failed', error);
					this.$Message.error(this.$t('ivcs.sendfailed'));
					console.log('shareResourceWithFileInfo error', error);
				}
			);
			let msgData = {
				url: data.url,
				type: 'file',
				fileName: data.fileName,
				name: data.name,
				suffix: data.suffix,
				size: data.size
			};
			console.log('fileData:', data);
			let msg = sendMessageToRecord('link', msgData, this.customer);
			this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
			this.setMsgTimer();
		},

		/*发送文件*/
		async sendFile(event) {
			const file = document.getElementById('file2').files[0];
			if (file.size > maxUploadFileSize) {
				this.$Message.error(this.$t('im.fileSizeError'));
				event.target.value = null;
				return;
			}
			let data = await uploadFile(file);
			if (data) {
				let message = '<a href="javascript:void(0)">' + data.name;
				this.sendFileToAgent(message, data);
			} else {
				this.$Message.error(this.$t('ivcs.sendfailed'));
			}
			event.target.value = null;
		},

		/*发送base64的image*/
		sendbase64img(image) {
			let data = uploadBase64Image(image);
			if (data) {
				return data;
			} else {
				this.$Message.error(this.$t('ivcs.sendfailed'));
				return null;
			}
		},

		/*提供给其他页面的返回事件*/
		back() {
			this.$emit('back');
		},

		beforeop() {},

		changeText: function(e) {
			this.inputMessage = $(e.currentTarget).text();
		},
		changeFixed(clientHeight) {
			this.$refs.homePage.style.height = clientHeight + 'px';
		},
		showOrHideTools() {
			//点击加号 显示或隐藏工具栏
			this.showTools = !this.showTools;
		},

		/*发送图片*/
		async sendPicture(event) {
			const file = document.getElementById('file').files[0];
			// 支持png jpg jpeg gif格式
			let imgTest = ['png', 'jpg', 'jpeg', 'gif'];
			let index = file.name.lastIndexOf('.');
			let ext = file.name.substr(index + 1).toLowerCase();
			if (imgTest.indexOf(ext) == -1) {
				this.$Message.error(this.$t('ivcs.imageSupportFormat'));
				return;
			}
			var fileSize = file.size;
			console.log('file filesize,', fileSize);
			if (fileSize > maxUploadFileSize) {
				this.$Message.error(this.$t('im.fileSizeError'));
				event.target.value = null;
				return;
			}

			let data = await uploadFile(file);
			if (data) {
				let message = '<img style="width:50px" src=' + data.url + '>';
				this.sendImageToAgent(message, data, true);
			} else {
				this.$Message.error(this.$t('ivcs.sendfailed'));
			}

			event.target.value = null;
		},

		/*滑动视图*/
		scrollToBottom() {
			var speak_height = $('.chat-message').height();
			speak_height = speak_height + 100;
			$('.chat-message,.ui-container').animate(
				{
					scrollTop: speak_height
				},
				500
			);
		},

		initEmotion() {
			var that = this;
			var editorTools = {
				emotion: '<div class="emotion" onmousedown="return false" unselectable="on"></div>'
			};
			var editorObject = {
				bindBody: false,
				options: {
					maxInputNum: 10000
				},
				init: function(selector, options) {
					var self = this;
					self.dom = $(selector);
					self.parentTextAreaDom = $(window.parent.document).find('#' + that.getQueryString('id'));
					self.initBody(self);
					self.initTools(self, options);
					self.initToolsEvents(self);
				},
				initTools: function(self, options) {
					if (!options || !options.tools) return;
					var toolsDom = self.dom.find('.tools');
					toolsDom.attr({
						unselectable: 'on',
						onmousedown: 'return false'
					});
					for (let i in options.tools) {
						var key = options.tools[i];
						toolsDom.append(editorTools[key]);
					}
					var emotion = self.dom.find('.tools .emotion');
					if (emotion.length > 0) {
						var navtools = $('<ul class="nav"></ul>');
						for (let i = 1, j = 0; i + j < 132; i += 10) {
							var li = $('<li></li>');
							for (let j = 0; j < 10 && i + j < 132; j++) {
								var index = i + j;
								var src = 'static/image/editor/emotion/qq/' + (index < 10 ? '00' + index : index < 100 ? '0' + index : index) + '.gif';
								li.append('<img src="' + src + '" onmousedown="return false" unselectable="on" >');
							}
							navtools.append(li);
						}
						emotion.append(navtools);
					}
				},
				initBody: function(self) {
					var bodyDom = self.dom.find('.body').attr('contentEditable', 'true');
					if (!self.bindBody) {
						self.bindBody = true;
						$('body').on('click', function(event) {
							that.stopPropagation(event);
							$(this)
								.find('.nav')
								.fadeOut();
						});
					}

					bodyDom.keyup(function() {
						var html = $(this).html();
						self.parentTextAreaDom.val(html);

						var len = html.length;
						self.dom.find('.bottom .inputInfo .doneNum').text(len);
						var unDoneLength = self.options.maxInputNum - len;
						self.dom.find('.bottom .inputInfo .undoNum').text(unDoneLength);
					});
				},
				initToolsEvents: function(self) {
					self.dom.find('.tools').on('click', '.emotion', function(event) {
						that.stopPropagation(event);
						$(this)
							.find('.nav')
							.show();
					});
					self.dom.find('.tools').on('click', '.emotion .nav img', function(event) {
						that.stopPropagation(event);
						var src = $(this).attr('src');
						var html = '<img src="' + src + '"> ';
						that.insertAtCursor(self.dom.find('.body')[0], html);
						self.dom.find('.body').keyup(); // 触发一下
						self.dom.find('.nav').hide();
					});
				}
			};

			editorObject.init('.main', {
				tools: ['emotion']
			});
		},
		getQueryString(name) {
			var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
			var r = window.location.search.substr(1).match(reg);
			if (r != null) return unescape(r[2]);
			return null;
		},
		stopPropagation(event) {
			if (event.stopPropagation) {
				// this code is for Mozilla and Opera
				event.stopPropagation();
			} else if (window.event) {
				// this code is for IE
				window.event.cancelBubble = true;
			}
		},
		insertAtCursor(dom, html) {
			var that = this;
			if (dom != document.activeElement) {
				dom.innerHTML = dom.innerHTML + html;
				that.inputMessage = $('.body')[0].innerHTML;
				return;
			}
			var sel, range;
			if (window.getSelection) {
				// IE9 或 非IE浏览器
				sel = window.getSelection();
				if (sel.getRangeAt && sel.rangeCount) {
					range = sel.getRangeAt(0);
					range.deleteContents();
					// Range.createContextualFragment() would be useful here but is
					// non-standard and not supported in all browsers (IE9, for one)
					var el = document.createElement('div');
					el.innerHTML = html;
					var frag = document.createDocumentFragment(),
						node,
						lastNode;
					while ((node = el.firstChild)) {
						lastNode = frag.appendChild(node);
					}
					range.insertNode(frag);
					// Preserve the selection
					if (lastNode) {
						range = range.cloneRange();
						range.setStartAfter(lastNode);
						range.collapse(true);
						sel.removeAllRanges();
						sel.addRange(range);
					}
					that.inputMessage = $('.body')[0].innerHTML;
				}
			} else if (document.selection && document.selection.type != 'Control') {
				// IE < 9
				document.selection.createRange().pasteHTML(html);
				that.inputMessage = $('.body')[0].innerHTML;
			}
		},

		return2Br(str) {
			return str.replace(/\r?\n/g, '<br />');
		},
		dateStr() {
			var nowDate = new Date();
			var h = nowDate.getHours();
			var dateF = {
				year: nowDate.getFullYear(),
				month: nowDate.getMonth() + 1,
				date: nowDate.getDate(),
				h: h < 12 ? '上午' + h : '下午' + (h - 12),
				m: nowDate.getMinutes(),
				s: nowDate.getMinutes()
			};
			return dateF.year + '/' + dateF.month + '/' + dateF.date + ' ' + dateF.h + ':' + dateF.m + ':' + dateF.s;
		},
		showFullImg(src) {
			$('.window-img').find('img')[1].src = src;
			this.showImg = true;
		},
		closeFullImg() {
			this.showImg = false;
		},
		inputFocus(e) {
			if (this.showTools) {
				this.showTools = false;
			}
		},

		// 格式化时间
		getFormatTime(date) {
			return formatMessageTime(date);
		},
		// 显示时间间隔
		setMsgTimer() {
			let now = Date.now();
			if (now - this.startMsgTime >= 300000) {
				this.messageData[this.messageData.length - 1].showTime = true;
				this.startMsgTime = now;
			}
		},

		// 根据消息 from，筛选坐席信息
		filterAgentByMsg(data) {
			let agentInfo = this.agentMembers.find(agent => agent.clientId === data.from);
			this.$store.commit('SET_AGENT_INFO', { ...agentInfo });
		}
	}
};
</script>

<style scoped lang="less">
@import '../../static/css/im.css';
.system-msg {
	span {
		padding: 10px;
		background-color: #ebebeb;
		border-radius: 22px;
		color: #777;
	}
}
.tool-box {
	position: absolute;
	display: flex;
	align-items: center;
	width: 96%;
	bottom: 10px;
	justify-content: space-between;
}
.right {
	display: flex;
}
</style>
